import { ReqParamInterface, ResParamInterface } from "../lib/interface";
import { PROTOCOL_NAME } from '../lib/constant';
export interface FnInterface { 
    (ctx: any, params: { [index: string]: any }): any;
}

export class RespObj { 
    constructor(public obj: any) { 
    }
    
    static parse(obj: any) { 
        return new RespObj(obj);
    }

    toString() { 
        if (!this.obj) { 
            return null;
        }
        return JSON.stringify(this.obj);
    }
}
export class ServerApi {
    private eventKey: string = '__api__';
    private socketConnection: any;
    private protocol: string = PROTOCOL_NAME;
    constructor(public socketreq: any, public fns: { [index: string]: FnInterface }) {
        if (!fns) {
            this.fns = {};
        }
    }

    init() {
        let self = this;
        if (self.socketreq.requestedProtocols.indexOf(self.protocol) < 0) {
            return self.socketreq.reject();
        }
        self.socketConnection = self.socketreq.accept(self.protocol, self.socketreq.origin);
        self.socketConnection.on('message', (msg: any) => { 
            let data: ReqParamInterface | null = null;
            if (msg.type == 'utf8') {
                try {
                    data = JSON.parse(msg.utf8Data);
                    return self.handle.bind(self)(data);
                } catch (err) {
                    console.error(err);
                    self.socketConnection.send(RespObj.parse({ code: 500, msg: "序列化json失败" }));
                }
            } 
            self.socketConnection.send(RespObj.parse({ code: 500, msg: "仅支持utf8类型" }));
        });
    }

    async handle(msg: ReqParamInterface) {
        let self = this;
        let __id__ = msg.__id__;
        let __method__ = msg.__method__;
        let args = msg.args;
        let resData: ResParamInterface = {
            __eventKey__: self.eventKey,
            __id__: __id__,
            __method__: __method__,
            code: 500,
            msg: '系统错误',
            data: null,
        }
        try {
            let fn = self.fns[__method__];
            if (!fn || typeof fn !== 'function') {
                let msg = '调用的函数不存在:' + __method__
                console.warn(msg);
                resData.code = 404;
                resData.msg = msg;
                return self.socketConnection.send(RespObj.parse(resData));
            }
            let ret = fn(self.socketConnection['ctx'], args);
            if (ret && ret.then && typeof ret.then == 'function') {
                ret = await ret;
            }
            //执行函数
            resData.code = 0;
            resData.msg = null;
            resData.data = ret;
            return self.socketConnection.send(RespObj.parse(resData));
        } catch (err) {
            if (err.code && err.msg) {
                resData.code = err.code;
                resData.msg = err.msg;
            } else {
                console.error(err);
            }
            return self.socketConnection.send(RespObj.parse(resData));
        }
    }

}